﻿using UnityEngine;
using System.Collections;

[AddComponentMenu("TagMachine/Entity/Fugitive")]
public class Fugitive : MonoBehaviour 
{
	public float BaseSpeedModifier			= 1.0f;
	public float ExpulsionDeceleration 		= 1.0f;
	
	public Color BaseColor 					{ get; set; }
	public bool IsSafe 						{ get; set; }
	public bool IsExpulsed 					{ get; private set; }

	private bool m_IsWinner					= false;

	private NavMeshAgent m_NavAgent 		= null;
	private MovingEntity m_MovingComponent 	= null;

	private Vector3 m_NormExpulsedForce		= Vector3.zero;
	private Vector3 m_ExpulsedForce			= Vector3.zero;

	void Awake()
	{
		m_NavAgent 							= transform.parent.GetComponent< NavMeshAgent >();
		m_MovingComponent 					= transform.parent.GetComponent< MovingEntity > ();
	}

	void Start()
	{
		renderer.material.color 			= BaseColor;

		GetComponent<EntityTrailGenerator>().Setup( BaseColor, m_NavAgent );
	}

	public void Activate()
	{		
		IsSafe 								= false;
		IsExpulsed 							= false;

		// Update character controller radius
		if ( m_MovingComponent != null )
		{
			m_MovingComponent.UpdateSpeed( BaseSpeedModifier );
			m_MovingComponent.UpdateSize( collider as CapsuleCollider );
			m_MovingComponent.enabled = true;
		}

		gameObject.SetActive( true );
	}

	public void SetLoser()
	{
		if ( m_IsWinner )
		{
			m_IsWinner = false;

			// GetComponent< SpriteRenderer >().sprite = BaseSprite;
		}
	}

	public void SetWinner()
	{
		if ( !m_IsWinner )
		{
			m_IsWinner = true;

			// GetComponent< SpriteRenderer >().sprite = WinnerSprite;
		}
	}
	
	// Update is called once per frame
	void Update () 
	{
		if ( IsExpulsed )
		{
			Vector3 ExpulsedDirection = m_ExpulsedForce.normalized;

			m_NavAgent.Move( m_ExpulsedForce * Time.deltaTime );
			m_ExpulsedForce -= m_NormExpulsedForce * ExpulsionDeceleration * Time.deltaTime;

			IsExpulsed = Vector3.Dot( ExpulsedDirection, m_ExpulsedForce ) > 0.0f;
		}
	}

	public void SafeAreaExpulsed( Vector3 _Expulsion ) 
	{
		IsExpulsed 				= true;
		m_ExpulsedForce 		= _Expulsion;
		m_NormExpulsedForce 	= _Expulsion.normalized;
	}
}
